package cn.tedu.ssm.service;


import cn.tedu.ssm.mapper.UserMapper;
import cn.tedu.ssm.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;



@Service
public class UserService {

    @Autowired
    private UserMapper mapper;

    public Map<String, Object> list(Integer page,Integer size){

        int limit = size == null||size<1?10:size;
        page = page == null || page <1?1:page;
        int offest = (page-1)*limit;

        List<User> users =mapper.find(offest,limit);

        Long count = mapper.count();

        Map<String,Object> map = new HashMap<>();
        map.put("users",users);
        map.put("count",count);

        return map;
    }

    public Long checkUsernameAndPassword(String username, String password) {
        if (!mapper.exists(username)) {
            // 账号不存在，返回 -1
            return -1L;
        }
        // 根据账号和密码查找其 ID
        Long id = mapper.findIdByUsernameAndPassword(username, password);
        if (id == null || id < 1) {
            // 账号和密码不匹配，返回 -2
            return -2L;
        }
        if (mapper.isDeleted(id)) {
            // 账号已经被删除，返回 -3
            return -3L;
        }
        if (mapper.isDisabled(id)) {
            // 账号已经被禁用，返回 -4
            return -4L;
        }
        return id;
    }


    public String findName(Long id){
        return mapper.findNameById(id);
    }

    /**
     * 查询所有非删除的用户名和用户状态
     * @return 用户名和用户状态
     */
    public Map<String,Object> findNameAndDisabled(){
        Map<String ,Object> map = new HashMap<>();
        List<User> userList = mapper.findNameAndDisabled();
        map.put("userList",userList);
        return map;
    }

    /**
     * 用户增加(用户名和姓名)
     * @param name:姓名userAdd
     * @param username:用户名
     * @return 用户增加的数量
     */
    public Integer userAdd(String name,String username,String password){
//        Long id = userMapper.findIdByUsernameAndPassword(username,password);
//        String uname = userMapper.findNameById(id);
        User user = mapper.findIdByUsername(username);
        if(!user.getDeleted())
            return mapper.userAdd(name,username, password);
        return 0;
    }

    /**
     * 根据用户名查询用户id
     * @param username:用户名
     */
    public Long findIdByUsername(String username){
        User user = mapper.findIdByUsername(username);
        if (user.getDeleted()){
            return user.getId();
        }
        return 0L;
    }

    /**
     * 返回用户数量
     * @return 用户数量
     */
    public Long userCount(){
        Long count = mapper.count();
        return count;
    }

    public User findInfoById(Long id){
        if (id >=0 ){
            return mapper.findInfoById(id);
        }
        return null;
    }

    public Long updateUser(Long id, String name, String password){
        return mapper.updateUser(id, name, password);
    }
}

